import axios from "axios";
import {ElMessage} from "element-plus";
import {useAdminStore} from '@/stores/modules/user/index.js'
import useAdminrouter from "@/router/index.js";


const BASE_URL = 'http://127.0.0.1:8000/' // 后端地址
const service = axios.create({
    baseURL: BASE_URL,
    timeout: 10000,   // 10秒
    headers: {
        'Content-Type': 'application/json',
    } // 配置请求头
})

// 2.请求拦截器
service.interceptors.request.use(config => {
    //发请求前做的一些处理，数据转化，配置请求头，设置token,设置loading等，根据需求去添加
    const useAdmin = useAdminStore()
    const token = useAdmin.$state.admin_token
    if (token) {
        config.headers.Authorization = 'Bearer' + ' ' + token
    }
    console.log("查看请求头", config.headers)
    return config
}, (error) => {
    console.log(error)
    return Promise.reject(error);
})


// 3.响应拦截器
service.interceptors.response.use((response) => {
    console.log(response)
    const router = useAdminrouter
    if (response.status == 200) {
        console.log('进入了200', response.data.code)
        if (response.data.code === 2000) {
            ElMessage.success(response.data.msg || response.data.results.msg)
            return response
        } else if (response.data.results && response.data.results.code === 2000) {
            ElMessage.success(response.data.msg || response.data.results.msg)
            return response
        } else if (response.data.code === 4000) {
            router.push({path: '/login'})
            console.log('进入了4000')
            console.log(response.data.msg)
            ElMessage.error(response.data.msg)
            return Promise.reject(response.data)
        }
    } else {
        return Promise.reject(response.data.msg)
    }
}, (error) => {
    /***** 接收到异常响应的处理开始 *****/
    console.log('拦截器的response', error)
    const router = useAdminrouter
    // console.log(,response)
    if (error.response.status == 401) {
        if (error.response.data.code === 'token_not_valid')
            ElMessage.error('会话过期，请重新登陆')
        router.push({path: '/login'})

    }else if(error.response.status == 400){
        ElMessage.error(error.response.data.msg)
    }
    else if (error.response.status == 404) {
        ElMessage.error(error.response.data.msg)
    }
    else if (error.response.status == 403) {
        ElMessage.error(error.response.data.msg)
    }
    //如果不需要错误处理，以上的处理过程都可省略
    return Promise.reject(error)
})
//4.导入文件
export default service